﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BaHuan.BusinessLayer;
using BaHuan.Common;
using BaHuan.Entities;
namespace BaHuan
{
    public partial class FrmDinhKhoanPhieuXuatHang : Form
    {
        #region Khai bao cuc bo
        public event FormClosePhieuXuatHangEventHandler formClosePhieuXuatHang = null;
        private ButToanMgt buttoanMgt = new ButToanMgt();
        private ChiNhanhCongTyMgt chinhanhcongtyMgt = new ChiNhanhCongTyMgt();
        private TaiKhoanKeToanMgt taikhoanketoanMgt = new TaiKhoanKeToanMgt();


        private PhieuXuatHang phieuxuathang;
        public PhieuXuatHang PhieuXuatHang
        {
            get { return this.phieuxuathang; }
            set { this.phieuxuathang = value; }
        }

        public long tongtien = 0;
        public long tien = 0;
        private long tienbaobi;
        public long TienBaoBi
        {
            get { return this.tienbaobi; }
            set { this.tienbaobi = value; }
        }
        #endregion
        
        #region Xu ly Load
        public FrmDinhKhoanPhieuXuatHang(long tient)
        {
            InitializeComponent();
            this.tien = tient;
        }

        private void FrmDinhKhoanPhieuXuatHang_Load(object sender, EventArgs e)
        {
            txtMSKH.ReadOnly = true;
            txtChiNhanh.ReadOnly = true;
            txtSoChungTu.ReadOnly = true;
            txtChiNhanh.ReadOnly = true;
            txtSoChungTu.Text = this.phieuxuathang.MaSo;
            txtMSKH.Text = this.phieuxuathang.KhachHang;

            List<ChiNhanhCongTy> lstChiNhanhCty = (from cn in GetAllChiNhanhCongTy()
                                                   where cn.Id == this.phieuxuathang.IdChiNhanhCongTy
                                                   select cn).ToList();
            txtChiNhanh.Text = lstChiNhanhCty[0].TenChiNhanh;

            cboSoTK.DataSource = GetAllTaiKhoanKeToan();
            cboSoTK.DisplayMember = "MaSoTK";
            cboSoTK.ValueMember = "TenTK";

            DataGridViewRow dataRow = new DataGridViewRow();
            DataGridViewComboBoxCell cboCell = new DataGridViewComboBoxCell();
            List<TaiKhoanKeToan> lstTaiKhoanKeToan = new List<TaiKhoanKeToan>();
            lstTaiKhoanKeToan = (from tk in GetAllTaiKhoanKeToan()
                                 where tk.MaSoTK == "131"
                                 select tk).ToList();

            cboCell.DataSource = lstTaiKhoanKeToan;
            cboCell.DisplayMember = "MaSoTK";
            cboCell.ValueMember = "TenTK";
            dataRow.Cells.Add(cboCell);

            cboCell = new DataGridViewComboBoxCell();
            cboCell.Items.Add("Nợ");
            cboCell.Items.Add("Có");
            cboCell.Value = "Nợ";
            dataRow.Cells.Add(cboCell);

            DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell();
            cell.Value = "";
            dataRow.Cells.Add(cell);

            cell = new DataGridViewTextBoxCell();
            cell.Value = 0;
            dataRow.Cells.Add(cell);

            dgvDinhKhoan.Rows.Add(dataRow);
        }

        public void EditOrRemoveDinhKhoan(string MaSo)
        {
            ResultObj resultObj = new ResultObj();

            List<ButToan> lst = (from p in GetAllButToan()
                                 where p.SoChungTu == MaSo
                                 select p).ToList();

            if (lst.Count > 0)
            {
                foreach (ButToan b in lst)
                {
                    b.IsEdited = 1;
                    resultObj = buttoanMgt.UpdateButToan(b);
                }
            }
        }
        #endregion

        #region Xu ly cac Button
        private void btnLuu_Click(object sender, EventArgs e)
        {
            for (int i = 1; i < dgvDinhKhoan.Rows.Count - 1; i++)
            {
                if ((dgvDinhKhoan.Rows[i].Cells[0].FormattedValue.ToString() == "" || dgvDinhKhoan.Rows[i].Cells[1].FormattedValue.ToString() == ""))
                {
                    MessageBox.Show("Vui lòng nhập đầy đủ thông tin trong danh sách !", "Thông báo");
                    return;
                }
            }

            if (dgvDinhKhoan.Rows[0].Cells[1].FormattedValue.ToString() == "Có")
            {
                MessageBox.Show("Định khoản " + dgvDinhKhoan.Rows[0].Cells[1].FormattedValue.ToString() + " phải chọn \"Nợ\" !!!", "Thông báo");
                return;
            }

            for (int i = 1; i < dgvDinhKhoan.Rows.Count - 1; i++)
            {
                if (dgvDinhKhoan.Rows[i].Cells[1].FormattedValue.ToString() == "Nợ")
                {
                    MessageBox.Show("Các định khoản khác " + dgvDinhKhoan.Rows[0].Cells[0].FormattedValue.ToString() + " phải chọn \"Có\" !!!", "Thông báo");
                    return;
                }
            }

            if (tien == tongtien)
            {
                ResultObj resultObj = new ResultObj();

                int rowIndex = -1;
                //check 131 yes or no
                for (int i = 0; i < dgvDinhKhoan.Rows.Count - 1; i++)
                {
                    if (dgvDinhKhoan.Rows[i].Cells[0].FormattedValue.ToString() == "131" && dgvDinhKhoan.Rows[i].Cells[1].FormattedValue.ToString() == "Nợ")
                    {
                        rowIndex = i;
                        break;
                    }
                }
                if (rowIndex == -1)
                {
                    MessageBox.Show("Chưa chọn định khoản 131 hoặc chưa chọn \"Nợ\" !!!", "Thông báo");
                    return;
                }

                EditOrRemoveDinhKhoan(phieuxuathang.MaSo);

                //Save
                for (int i = 0; i < dgvDinhKhoan.Rows.Count - 1; i++)
                {
                    if (i != rowIndex && dgvDinhKhoan.Rows[i].Cells[3].FormattedValue.ToString() != "0")
                    {
                        ButToan buttoan = new ButToan();
                        buttoan.NgayThang = dtpNgay.Value;
                        buttoan.ChiNhanh = txtChiNhanh.Text;
                        buttoan.MaSoKhachHang = txtMSKH.Text;
                        buttoan.DienGiai = txtNoiDung.Text;
                        buttoan.SoChungTu = txtSoChungTu.Text;
                        buttoan.TKGoc = dgvDinhKhoan.Rows[rowIndex].Cells[0].FormattedValue.ToString();
                        buttoan.TKDoiUng = dgvDinhKhoan.Rows[i].Cells[0].FormattedValue.ToString();
                        buttoan.GhiNo = Convert.ToInt64(dgvDinhKhoan.Rows[i].Cells[3].Value.ToString());
                        buttoan.GhiCo = 0;
                        resultObj = buttoanMgt.SaveNewButToan(buttoan);

                        buttoan = new ButToan();
                        buttoan.NgayThang = dtpNgay.Value;
                        buttoan.ChiNhanh = txtChiNhanh.Text;
                        buttoan.MaSoKhachHang = txtMSKH.Text;
                        buttoan.DienGiai = txtNoiDung.Text;
                        buttoan.SoChungTu = txtSoChungTu.Text;
                        buttoan.TKGoc = dgvDinhKhoan.Rows[i].Cells[0].FormattedValue.ToString();
                        buttoan.TKDoiUng = dgvDinhKhoan.Rows[rowIndex].Cells[0].FormattedValue.ToString();
                        buttoan.GhiNo = 0;
                        buttoan.GhiCo = Convert.ToInt64(dgvDinhKhoan.Rows[i].Cells[3].Value.ToString());
                        resultObj = buttoanMgt.SaveNewButToan(buttoan);
                    }
                }

                if (resultObj.ReturnCode > 0)
                {
                    MessageBox.Show("Lưu thành công", "Thông báo");
                    this.Close();
                    if (formClosePhieuXuatHang != null)
                        formClosePhieuXuatHang(true);
                }
                else if (resultObj.ReturnCode == Definitions.DUPLICATED_VALUE)
                    MessageBox.Show("Dữ liệu bị trùng", "Thông báo");
                else
                    MessageBox.Show("Thất bại");
            }
            else
            {
                MessageBox.Show("Số tiền định khoản không đúng", "Thông báo");
            }
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion

        #region Xu ly cac su kien
        private void dgvDinhKhoan_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex > -1)
            {
                ResultObj result = new ResultObj();
                
                string tenTK = dgvDinhKhoan.Rows[e.RowIndex].Cells[0].Value.ToString();

                dgvDinhKhoan.Rows[e.RowIndex].Cells[2].Value = tenTK;
                int soDinhKhoan = Convert.ToInt32(dgvDinhKhoan.Rows[e.RowIndex].Cells[0].FormattedValue.ToString());
                switch (soDinhKhoan)
                {
                    case 511:
                        dgvDinhKhoan.Rows[e.RowIndex].Cells[3].Value = this.phieuxuathang.TongTienHang.ToString();
                        break;
                    case 3331:
                        dgvDinhKhoan.Rows[e.RowIndex].Cells[3].Value = this.phieuxuathang.TienVAT.ToString();
                        break;
                    case 153:
                        dgvDinhKhoan.Rows[e.RowIndex].Cells[3].Value = this.tienbaobi.ToString();
                        break;
                    default:
                        dgvDinhKhoan.Rows[e.RowIndex].Cells[3].Value = 0;
                        break;

                }
            }

            if (e.ColumnIndex == 3 && e.RowIndex > -1 && dgvDinhKhoan.Rows[e.RowIndex].Cells[0].FormattedValue.ToString() != "131")
            {
                if (dgvDinhKhoan.Rows[e.RowIndex].Cells[3].Value == null)
                    dgvDinhKhoan.Rows[e.RowIndex].Cells[3].Value = 0;
            }

            int rowIndex = -1;
            for (int i = 0; i < dgvDinhKhoan.Rows.Count - 1; i++)
            {
                if (dgvDinhKhoan.Rows[i].Cells[0].FormattedValue.ToString() == "131")
                {
                    rowIndex = i;
                    break;
                }
            }
            if (rowIndex == -1)
                return;
            long tongMotBaMot = 0;
            for (int j = 1; j < dgvDinhKhoan.Rows.Count - 1; j++)
            {
                if (dgvDinhKhoan.Rows[j].Cells[0].FormattedValue.ToString() != "131" && dgvDinhKhoan.Rows[j].Cells[3].Value != null)
                {
                    tongMotBaMot += Convert.ToInt64(dgvDinhKhoan.Rows[j].Cells[3].Value.ToString());
                }
            }

            tongtien = tongMotBaMot;
            dgvDinhKhoan.Rows[rowIndex].Cells[3].Value = tongMotBaMot;
        }

        private void dgvDinhKhoan_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = false;
        }

        private void XoaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dgvDinhKhoan.CurrentRow != null)
            {
                if (dgvDinhKhoan.CurrentRow.Index != (dgvDinhKhoan.Rows.Count - 1))
                {
                    dgvDinhKhoan.Rows.RemoveAt(dgvDinhKhoan.CurrentRow.Index);
                    long sotien = Convert.ToInt64(dgvDinhKhoan.Rows[dgvDinhKhoan.CurrentRow.Index].Cells[3].Value.ToString());
                    for (int i = 0; i < dgvDinhKhoan.Rows.Count; i++)
                    {
                        if (dgvDinhKhoan.Rows[i].Cells[0].FormattedValue.ToString() == "131")
                        {
                            long sotien131 = Convert.ToInt64(dgvDinhKhoan.Rows[i].Cells[3].Value.ToString());
                            long result = sotien131 - sotien;
                            this.tongtien = result;
                            dgvDinhKhoan.Rows[i].Cells[3].Value = result;
                            break;
                        }

                    }
                    
                }
            }
        }

        private void dgvDinhKhoan_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                DataGridView.HitTestInfo hti = dgvDinhKhoan.HitTest(e.X, e.Y);
                if (hti.Type == DataGridViewHitTestType.Cell)
                {
                    dgvDinhKhoan.ClearSelection();
                    dgvDinhKhoan.CurrentCell = dgvDinhKhoan.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    dgvDinhKhoan.ContextMenuStrip = contextMenuStrip1;
                }
            }
        }
        #endregion

        #region Lay cac List
        public List<ButToan> GetAllButToan()
        {
            ResultObj resultObj = new ResultObj();

            resultObj = buttoanMgt.GetAllButToan();
            List<ButToan> listButToan = (List<ButToan>)resultObj.Result;

            return listButToan;
        }

        public List<TaiKhoanKeToan> GetAllTaiKhoanKeToan()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = taikhoanketoanMgt.GetAllTaiKhoanKeToan();
            List<TaiKhoanKeToan> listTaiKhoanKeToan = (List<TaiKhoanKeToan>)resultObj.Result;
            return listTaiKhoanKeToan;
        }

        public List<ChiNhanhCongTy> GetAllChiNhanhCongTy()
        {
            ResultObj resultObj = new ResultObj();
            resultObj = chinhanhcongtyMgt.GetAllChiNhanhCongTy();
            List<ChiNhanhCongTy> listChiNhanhCongTy = (List<ChiNhanhCongTy>)resultObj.Result;
            return listChiNhanhCongTy;
        }
        #endregion  
    }
}
